<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px"
      class="frominfo">
      <!-- 搜索栏部分 -->
      <div class="from-item">
        <el-form-item label="微信名称" prop="wcUserName">
          <el-input v-model="queryParams.wcUserName" @keyup.enter.native="handleQuery" placeholder="请输入好友微信名称"
            clearable />
        </el-form-item>
        <el-form-item label="微信备注" prop="wcNoteName">
          <el-input v-model="queryParams.wcNoteName" @keyup.enter.native="handleQuery" placeholder="请输入好友备注名" clearable />
        </el-form-item>
        <el-form-item label="聊天时间" prop="beginTime">
          <el-date-picker v-model="chatTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>

        <el-form-item label="标签" prop="labelName">
          <el-select v-model="labelName" multiple placeholder="请选择标签">
              <el-option
                v-for="item in friendInfo"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictLabel">
              </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否在网" prop="interState">
          <el-select v-model="queryParams.interState" placeholder="请选择" clearable>
            <el-option v-for="dict in dict.type.sys_network_status" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>


        <el-form-item label="所属人员" prop="wcName" v-if="!common">
          <el-input v-model="queryParams.wcName" @keyup.enter.native="handleQuery" placeholder="请输入助手微信名" clearable />
        </el-form-item>

      </div>
      <div class="from-Btn">
        <el-form-item>
          <el-button class="blue-button" type="primary" icon="el-icon-search" size="mini"
            @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </div>
    </el-form>

    <!-- 导出按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button class="blue-button" plain icon="el-icon-upload2" size="mini" @click="handleExport"
          v-hasPermi="['arbit:wcfriendinfo:export']" style="background-color: rgb(0, 120, 251);
    color: rgb(255, 255, 255);
    border-color: rgb(0, 120, 251);">批量导出</el-button>
      </el-col>
    </el-row>

    <!-- 信息框 -->
    <el-table v-loading="loading" :data="friendList" @selection-change="handleSelectionChange" ref="elTable">
      <el-table-column type="selection" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="微信名称" prop="wcUserName" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="微信备注" prop="wcNoteName" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="是否在网" prop="interState" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_network_status" :value="scope.row.interState"/>
        </template>
      </el-table-column>
      <el-table-column label="标签" prop="friendLabel" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="微信所属人员" prop="wcName" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="最近聊天时间" prop="lastChatTime" align="center" :show-overflow-tooltip="true" width="180">
          <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastChatTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
      </el-table-column>
      <el-table-column align="center" width="120" class-name="small-padding fixed-width" v-if="checkPermi(['massage:massage:getMags'])">
        <template slot="header">
          <span>聊天详情</span>
          <el-tooltip class="item" effect="dark" content="进入操作各个微信号" placement="top">
            <i class="el-icon-warning" style="color:#818e96;"></i>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
           <span style="cursor: pointer;color:#0078fb" @click="golink(scope.row.wcId,scope.row.wcUserId,scope.row.wcName,scope.row.wcUserName)">详情</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>
  
<script>

import request from '@/utils/request'
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { checkPermi } from "@/utils/permission";
export default {
    name: "WcFriendInfo",
    dicts: ['sys_network_status'],
    data() {
        return {
            radio: '1',
            exportDialogVisible: false,
            selectedAssistIds: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 助手信息表格数据
            friendList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            labelName:[],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                wcId: null,
                deptId:null,
                wcName:null,
                wcUserName: null,
                wcNoteName: null,
                wcUserRegion: null,
                friendLabel:null,
                interState: null,
                beginTime: null,
                endTime: null,
            },
            chatTime:[],
            common:false,
            lable:[],
            friendInfo:[],
        };
    },
    mounted() {
        if(this.$store.state.user.roles.includes("common")){
           this.common=true
        }
        this.getList();
        //this.getLable();
        this.friendLabel()
    },
    methods: {
        checkPermi,
        getLable(){
          getLableInfo().then(res=>{
            //console.log(res)
            if(res.code==200){
              this.lable=res.data.map(item => {
                return item.lableName
              })
            }
          })
        },
        friendLabel(){
            friendLabel().then(res => {
              //console.log(res)
              if(res.code==200){
                this.friendInfo=res.data
              }
            });
        },
        golink(wxid,userid,name,username){
          this.$router.push({ path:"/market/detial/index/",name:'frienddetial',query: { userid,wxid,groupid:'',name,username}}).catch(()=>{});
        },
        /** 查询好友信息列表 */
        getList() {
            this.loading = true;
            var lable=""
            if(this.labelName!=null){
                this.labelName.forEach(element => {
                  lable+=","+element
                })
            }
            this.queryParams.friendLabel=lable.substring(1)
            listWcFriendInfo(this.queryParams).then(res => {
                if (res['success']) {
                    const dt = res['data'];
                    this.total = dt['total'];
                    this.friendList = dt['records'];
                }
                this.loading = false;
            });
            setTimeout(()=>{
                this.loading = false;
            },2000)
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.beginTime=null
            this.queryParams.endTime=null
            if(this.chatTime!=''&&this.chatTime!=null){
              this.queryParams.beginTime=this.chatTime[0]+' 00:00:00'
              this.queryParams.endTime=this.chatTime[1]+' 23:59:59'
            }
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.chatTime=[]
            this.labelName=[]
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          //console.log(selection)
          this.selectAll=false
          this.ids = selection.map(item => item.id)
          this.single = selection.length!==1
          this.multiple = !selection.length
          this.selection=selection
        },
        handleSelectAll(selection){
          this.selectAll=false
          if(selection!=''){
              this.ids=selection.map(item => item.id)
              this.selectAll=true
          }
        },
        /** 导出按钮操作 */
        handleExport() {
          if(this.ids==''){
            this.$message({
                message: '请选择要导出的数据！',
                type: 'warning'
            });
            return
          }
          if(this.selectAll){
            this.download('arbit/wcfriend_info/export', {
               ...this.queryParams
            }, `wcFriendInfo_${new Date().getTime()}.xlsx`)
          }else{
              this.exportExcel()
          }
         
        },
        exportExcel() {
          const data = [["id","微信名称", "微信备注", "是否在网","标签", "微信所属人员", "最近聊天时间"],];
          this.selection.forEach(element => {
            var arr=[element.id,element.wcUserName,element.wcNoteName,element.interState==0?'离线':'在线',element.lableName,element.wcUserName,element.lastChatTime]
            data.push(arr)
          });
          
          // 将数据转换为工作表
          const ws = XLSX.utils.aoa_to_sheet(data);
     
          // 创建工作簿并添加工作表
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
     
          // 生成Excel文件
          const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
     
          // 字符串转ArrayBuffer
          function s2ab(s) {
            const buf = new ArrayBuffer(s.length);
            const view = new Uint8Array(buf);
            for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
          }
     
          // 保存文件
          saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), `wcFriendInfo_${new Date().getTime()}.xlsx`);
        }
    }
};

/** js请求 调用 */

// 查询微信好友信息列表
export function listWcFriendInfo(query) {
  return request({
    url: '/arbit/wcfriend_info/page',
    method: 'get',
    params: query
  })
}
// 获取微信标签信息
export function getLableInfo() {
  return request({
    url: '/wxassistant/wcuser_lable_copy/pagex',
    method: 'get',
  })
}
//获取所有好友标签
export function friendLabel() {
  return request({
    url: '/label/relevance/type/friend_label',
    method: 'GET',
  })
}
</script>

<style scoped lang="scss">
.frame {
  width: 100%;
  height: 100%;
  border: 1px solid rgb(167, 166, 164);

  span {
    margin: 10px 10px;
  }
}

.choice {
  margin-top: 20px;
  margin-bottom: 20px;

  .choice_one {
    color: red;
  }

  span {
    margin-right: 10px;
  }
}

.app-container {
  background-color: #f6f9fb;
}

.frominfo {
  display: flex;
  background-color: #fff;
  padding: 10px;
  padding-bottom: 0;
  margin-bottom: 20px;

  .from-item {
    display: flex;
    flex-wrap: wrap;
  }

  .from-Btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    // width: 20%;

    .el-button+.el-button {
      margin-left: 0px;
    }
  }
}

//  背景不重叠
.pagination-container {
  position: relative;
  height: 50px;
  margin-bottom: 0px;
  margin-top: 0px;
  padding: 10px 20px !important;
}
</style>